import java.io.*;
import java.net.*;

public class StopAndWaitClient {
    private static final String SERVER_IP = "127.0.0.1";
    private static final int SERVER_PORT = 9876;

    public static void main(String[] args) {
        DatagramSocket clientSocket = null;
        try {
            clientSocket = new DatagramSocket();
            InetAddress serverAddress = InetAddress.getByName(SERVER_IP);

            // Establish connection
            sendEmptyPacket(clientSocket, serverAddress, SERVER_PORT);

            // Send file
            FileInputStream fileInputStream = new FileInputStream("D:/123.txt");
            byte[] buffer = new byte[1023];
            int sequenceNumber = 0;

            while (fileInputStream.read(buffer) != -1) {
                byte[] sendData = new byte[buffer.length + 1];
                sendData[0] = (byte) sequenceNumber;
                System.arraycopy(buffer, 0, sendData, 1, buffer.length);

                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, SERVER_PORT);
                clientSocket.send(sendPacket);

                // Wait for acknowledgment
                byte[] ackData = new byte[1];
                DatagramPacket ackPacket = new DatagramPacket(ackData, ackData.length);
                clientSocket.receive(ackPacket);

                sequenceNumber++;
            }

            // Send an empty packet to signal the end of the file
            sendEmptyPacket(clientSocket, serverAddress, SERVER_PORT);

            System.out.println("File sent successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (clientSocket != null && !clientSocket.isClosed()) {
                clientSocket.close();
            }
        }
    }

    private static void sendEmptyPacket(DatagramSocket socket, InetAddress serverAddress, int serverPort) throws IOException {
        byte[] emptyData = new byte[1];
        DatagramPacket emptyPacket = new DatagramPacket(emptyData, emptyData.length, serverAddress, serverPort);
        socket.send(emptyPacket);
    }
}
